import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_todolist/db/table/task_table.dart';
import 'package:flutter_todolist/db/table/task_type_table.dart';
import 'package:flutter_todolist/helper/event/event_bus_name.dart';
import 'package:flutter_todolist/helper/event/event_helper.dart';
import 'package:flutter_todolist/pages/home/task_controller.dart';
import 'package:flutter_todolist/pages/home/task_type_controller.dart';
import 'package:get/get.dart';

import '../../util.dart';

class TaskOverView extends StatefulWidget {
  const TaskOverView({Key? key}) : super(key: key);

  @override
  State<TaskOverView> createState() => _TaskOverViewState();
}

class _TaskOverViewState extends State<TaskOverView> with AutomaticKeepAliveClientMixin {

  final taskOverViewCtrl = Get.put(TaskOverViewController());

  @override
  void initState() {
    EventHelper.on(EventBusName.taskOverViewUpdate, (args) {
      taskOverViewCtrl.getTaskStat();
    });

    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return content();
  }

  Widget content() {
    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 10),
      width: MediaQuery.of(context).size.width,
      child: CustomScrollView(
        slivers: <Widget>[
          SliverToBoxAdapter(
            child: Container(
              margin: const EdgeInsets.only(left: 10, top: 15, bottom: 0),
              child: const Text(
                'Projects',
                style: TextStyle(
                    fontSize: 13,
                    fontWeight: FontWeight.w600,
                    color: CustomColors.TextSubHeader),
              ),
            ),
          ),
          Obx(() => SliverGrid(
              delegate: SliverChildBuilderDelegate((context, index) {
                return GestureDetector(
                  onTap: () {
                    // taskCount();
                  },
                  child: taskItem(taskOverViewCtrl.taskStat[index]['taskType'], taskOverViewCtrl.taskStat[index]['count']),
                );
              },
              childCount: taskOverViewCtrl.taskStat.length),
              gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
                  crossAxisCount: 2
              )
          )),
        ],
      ),
    );
  }

  Widget taskItem(TaskType taskTypeItem, int taskCount) {
    return Container(
        decoration: const BoxDecoration(
          borderRadius: BorderRadius.all(
            Radius.circular(5.0),
          ),
          boxShadow: [
            BoxShadow(
              color: CustomColors.GreyBorder,
              blurRadius: 10.0,
              spreadRadius: 5.0,
              offset: Offset(0.0, 0.0),
            ),
          ],
          color: Colors.white,
        ),
        margin: const EdgeInsets.all(10),
        height: 150.0,
        child: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              Container(
                width: 65,
                height: 65,
                decoration: BoxDecoration(
                  color: Color(taskTypeItem.color ?? CustomColors.YellowBackground.value).withOpacity(0.2),
                  borderRadius: const BorderRadius.all(
                    Radius.circular(50.0),
                  ),
                ),
                child: Align(
                  child: Image.asset(
                    'assets/images/${taskTypeItem.icon}.png',
                    width: 30,
                    height: 30,
                    fit: BoxFit.cover,
                    color: Color(taskTypeItem.color ?? CustomColors.OrangeIcon.value),
                  ),
                ),
              ),
              const SizedBox(height: 5),
              Text(
                taskTypeItem.title ?? '',
                style: const TextStyle(
                    fontSize: 17,
                    color: CustomColors.TextHeaderGrey,
                    fontWeight: FontWeight.w600),
              ),
              const SizedBox(height: 8),
              Text(
                '$taskCount Tasks',
                style: const TextStyle(
                    fontSize: 9,
                    color: CustomColors.TextSubHeaderGrey),
              ),
            ],
          ),
        ));
  }

  @override
  bool get wantKeepAlive => true;

}

class TaskOverViewController extends GetxController {

  TaskController taskCtrl = Get.find<TaskController>();
  TaskTypeController taskTypeCtrl = Get.find<TaskTypeController>();
  final taskStat = <Map<String, dynamic>>[].obs;

  @override
  void onInit() {
    getTaskStat();
    super.onInit();
  }

  @override
  void onClose() {
    super.onClose();
  }

  void getTaskStat() {
    taskStat.clear();

    List<Task> taskList = taskCtrl.taskList;
    List<TaskType> taskTypeList = taskTypeCtrl.taskTypeList;

    for (var element in taskTypeList) {
      taskStat.add({
        "count": 0,
        "taskType": element
      });
    }

    for (var taskCountItem in taskStat) {
      TaskType taskType = taskCountItem['taskType'];

      // debugPrint('当前taskType类型：${taskType.toJson()}');

      for (var taskItem in taskList) {
        // debugPrint('当前task：${taskItem.toJson()}');
        if (taskItem.type == taskType.typeId) {
          // debugPrint('类型+1');
          taskCountItem['count'] = taskCountItem['count'] + 1;
        }
      }

    }

    update();

  }
}
